import axios from "axios";
import { ElMessage } from "element-plus";
import loading from "../loading";

const service = axios.create({
    timeout: 600000, // 请求超时时间
    headers: {
        "Content-Type": "application/json",
    }
})

// const whiteList = ["/ds/editor/waterrepair", "/ds/editor/batchcreate"]

// 请求拦截器
service.interceptors.request.use(
    config => {
        // @ts-ignore
        // if (whiteList.includes(config.url)) {
        //     loading.showLoading("提交中，请稍后...")
        // }
        // 添加请求头
        const token = localStorage.getItem("Authorization")
        if (token) {
            config.headers.Authorization = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // @ts-ignore
        // if (whiteList.includes(response.config.url)) {
        //     setTimeout(() => {
        //         loading.closeLoading()
        //     }, 200)
        // }
        const { data } = response
        if (data.status == '未登录') {
            window.location.href = "/login.html";
            ElMessage.error('未登录');
            return;
        }
        if (data.code == 200 || data.status == 'ok' || data.code == '1000') {
            return data
        } else {
            // const msg = checkStatus(data.code, data.status);
            ElMessage.error(data.status);
            return response;
        }
    },
    error => {
        const { status, data } = error.response
        
        if (data.status == '登录状态已过期' || data.status == '未登录') {
            window.location.href = "/login.html";
            ElMessage.warning("登录状态已过期，请重新登录。")
            return;
        }
        if (status === 500 || status != "ok") return ElMessage.error(data.status)
        return Promise.reject(error)
    }
)
export default service